package com.vast.ui.component.socketinterface.launchar;

import java.util.concurrent.Executor;
import com.vast.ui.component.controller.TableViewerController;
import com.vast.ui.component.socketinterface.listner.IReceiveListener;
import com.vast.ui.component.socketinterface.listner.ISocketConnectionListener;
import com.vast.ui.component.socketinterface.request.Request;
import com.vast.ui.component.socketinterface.request.RequestQueue;
import com.vast.ui.component.socketinterface.serverblocking.BlockingServer;
import com.vast.ui.component.socketinterface.servercommon.IServer;
import com.vast.ui.component.toolbar.ToolBarAction;
import com.vast.ui.component.util.ConsoleLoggerSingleton;
import com.vast.ui.component.util.Logger;
import com.vast.ui.panel.iopanel.views.ViewPart;

public class InterfaceLaunchar extends ToolBarAction implements ISocketConnectionListener{
	public  int            serverPort = 30000;
	public  IServer        server;
	public  TableViewerController controller;
	public  RequestQueue   sendRequestQueue;
	private boolean        isServerActive = false;
	private final Executor executor;
	public  final Logger   logger;
	
	public InterfaceLaunchar(ViewPart view, TableViewerController controller, int serverPort) {
		super(view);
		this.serverPort = serverPort;
		this.controller = controller;	
		this.logger     = ConsoleLoggerSingleton.getInstance();
		this.executor   = new Executor() {
			public void execute(Runnable r) {
				new Thread(r).start();
			}
		};
		this.server = new BlockingServer (serverPort, sendRequestQueue, executor);
		server.addReceiveListener(controller);
		server.addSocketConnectionListener(this);
		controller.init(8, 4, 0xff00ff);
	}
	
	public void sendRequest(Request request) {
		server.send(request);
	}
	
	public void openConnection() {
		addAction();
	}
	
	public void closeConnection() {
		stopAction();
	}
	
	public void addReceiveListener(IReceiveListener listener){
		server.addReceiveListener(listener);
	}
	
	public void removeReceiveListener(IReceiveListener listener) {
		server.removeReceiveListener(listener);
	}

	public synchronized void setServerActive(boolean isServerActive) {
		this.isServerActive = isServerActive;
	}

	public boolean isServerActive() {
		return isServerActive;
	}

	@Override
	public void addAction() {
		// TODO Auto-generated method stub
		controller.add(0);
		
	}

	@Override
	public void deleteAction() {
		// TODO Auto-generated method stub
		controller.delete();
	}

	@Override
	public void startAction() {
		// TODO Auto-generated method stub
		setStopActionEnable();
		if(!isServerActive()) {
			setServerActive(true);
			server.openConnection();
		}
	}

	@Override
	public void stopAction() {
		// TODO Auto-generated method stub
		setStartActionEnable();
		server.closeConnection();
		setServerActive(false);
	}

}
